package cn.good.yan.config.t3;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import javax.validation.constraints.NotNull;
import java.net.URI;
import java.util.Arrays;
import java.util.List;

/**
 * 自定义 - 过滤器
 *
 * @author shengren.yan
 * @create 2024/3/20
 */
@Component
@Slf4j
public class RequestLogGatewayFilterFactory extends AbstractGatewayFilterFactory<RequestLogGatewayFilterFactory.Config> {

    public RequestLogGatewayFilterFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        List<String> list = Arrays.asList("name");
        return  list;
//        return Lists.newArrayList("name");
    }

    /**
     * 定义请求过滤器
     * 访问：http://localhost:8080/one/aaa/test1?ver=yy，会请求成功，http://localhost:8080/one/aaa/test1?ver=11会失败，因为自定义过滤器过滤掉
     *
     * @param config
     * @return {@code GatewayFilter}
     */
    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {

            // 获取请求路径
            String path = exchange.getRequest().getPath().toString(); // aaa/test1
            URI uri = exchange.getRequest().getURI(); // 全路径的url
            System.err.println(String.format("获取到请求路径：%s", uri.toString()));
            // 如果请求路径以“/v1”开头，则截取掉第一个路径段
            if (path.startsWith("/v1")) {
                path = path.substring("/v1".length());
            }

            // 创建新的请求对象，并将新路径设置为请求路径
            ServerHttpRequest newRequest = exchange.getRequest().mutate()
                    // 截取路径
                    .path(path)
                    .build();

            // 使用新请求对象创建新的ServerWebExchange对象
            ServerWebExchange newExchange = exchange.mutate()
                    .request(newRequest)
                    .build();
            System.err.println(String.format("获取到新的请求路径：%s", newExchange.getRequest().getURI()));

            // ------------------------------------------------- 案例

            String name = config.getName();
            log.info("从配置文件中获取到的 enabled 的值=[{}].", name);
            String ver = exchange.getRequest().getQueryParams().getFirst("ver");
            System.out.println("参数：" + ver);
            if (StringUtils.isNotEmpty(ver)) {
                if (ver.equals("yy")) {
                    return chain.filter(exchange);
                } else {
                    // 返回600
                    exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND);
                    return exchange.getResponse().setComplete();
                }
            }
            // 继续执行过滤器链
            return chain.filter(exchange);
        };
    }

    // 配置类，属性用于接收配置文件中的值
    @Data
    public static class Config {
        // 自定义过滤器的参数
        @NotNull
        private String name;
    }

}
